from django.contrib.admin.sites import AdminSite
from django.contrib.auth.signals import user_logged_in
from django.dispatch import receiver
from serverworker.models import testmod,Loginlog

class AdminLoginMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        return response

    @receiver(user_logged_in)
    def _log_login(sender, request, user, **kwargs):
        #if hasattr(request, 'path') and request.path.startswith(AdminSite().get_urls()[0].pattern):
        dic_login = {'user':user.username,
                    'pcname':request.META['COMPUTERNAME'],
                     'os':request.META['OS'],
                     'remot':request.META['REMOTE_HOST'],
                     'addr':request.META['REMOTE_ADDR'],
                     #'ua':request.META['HTTP_SEC_CH_UA'],
                     'ag':request.META['HTTP_USER_AGENT']}
        print(dic_login)

        fun = Loginlog.objects.create(
            user=user.username,
            pcname=request.META['COMPUTERNAME'],
            os=request.META['OS'],
            remot=request.META['REMOTE_HOST'],
            addr=request.META['REMOTE_ADDR'],
            ua='-',
            ag=request.META['HTTP_USER_AGENT'],
            status=True,
        )
        print("log_login：", fun.user)

